import { request } from "./index";
import type { Persona, PageResponse } from "@/types/chat";

// 人格API接口
export const personaApi = {
  /**
   * 获取人格列表
   */
  getPersonas(params?: {
    category?: string;
    isActive?: boolean;
    isPublic?: boolean;
    page?: number;
    size?: number;
  }): Promise<Persona[]> {
    return request.get("/personas", params);
  },

  /**
   * 获取指定人格信息
   */
  getPersona(personaId: string): Promise<Persona> {
    return request.get(`/personas/${personaId}`);
  },

  /**
   * 创建自定义人格
   */
  createPersona(data: {
    name: string;
    description: string;
    avatar?: string;
    systemPrompt: string;
    category: string;
    tags: string[];
    isPublic?: boolean;
    config?: Record<string, any>;
  }): Promise<Persona> {
    return request.post("/personas", data, {
      showLoading: true,
      loadingText: "创建人格中...",
    });
  },

  /**
   * 更新人格信息
   */
  updatePersona(
    personaId: string,
    data: Partial<{
      name: string;
      description: string;
      avatar: string;
      systemPrompt: string;
      category: string;
      tags: string[];
      isPublic: boolean;
      isActive: boolean;
      config: Record<string, any>;
    }>,
  ): Promise<Persona> {
    return request.put(`/personas/${personaId}`, data, {
      showLoading: true,
      loadingText: "更新中...",
    });
  },

  /**
   * 删除人格
   */
  deletePersona(personaId: string): Promise<void> {
    return request.delete(
      `/personas/${personaId}`,
      {},
      {
        showLoading: true,
        loadingText: "删除中...",
      },
    );
  },

  /**
   * 克隆人格
   */
  clonePersona(personaId: string, newName: string): Promise<Persona> {
    return request.post(
      `/personas/${personaId}/clone`,
      { newName },
      {
        showLoading: true,
        loadingText: "克隆中...",
      },
    );
  },

  /**
   * 上传人格头像
   */
  uploadAvatar(personaId: string, file: File): Promise<{ avatarUrl: string }> {
    const formData = new FormData();
    formData.append("avatar", file);

    return request.upload(`/personas/${personaId}/avatar`, formData, {
      showLoading: true,
      loadingText: "上传中...",
    });
  },

  /**
   * 获取人格分类
   */
  getCategories(): Promise<
    Array<{
      id: string;
      name: string;
      description: string;
      icon: string;
      count: number;
    }>
  > {
    return request.get("/personas/categories");
  },

  /**
   * 获取推荐人格
   */
  getRecommendedPersonas(limit = 10): Promise<Persona[]> {
    return request.get("/personas/recommended", { limit });
  },

  /**
   * 获取热门人格
   */
  getPopularPersonas(
    period: "day" | "week" | "month" = "week",
    limit = 10,
  ): Promise<Persona[]> {
    return request.get("/personas/popular", { period, limit });
  },

  /**
   * 搜索人格
   */
  searchPersonas(
    query: string,
    options?: {
      category?: string;
      tags?: string[];
      isPublic?: boolean;
      page?: number;
      size?: number;
    },
  ): Promise<PageResponse<Persona>> {
    return request.get("/personas/search", {
      query,
      ...options,
    });
  },

  /**
   * 收藏人格
   */
  favoritePersona(personaId: string): Promise<void> {
    return request.post(`/personas/${personaId}/favorite`);
  },

  /**
   * 取消收藏人格
   */
  unfavoritePersona(personaId: string): Promise<void> {
    return request.delete(`/personas/${personaId}/favorite`);
  },

  /**
   * 获取收藏的人格
   */
  getFavoritePersonas(): Promise<Persona[]> {
    return request.get("/personas/favorites");
  },

  /**
   * 评价人格
   */
  ratePersona(
    personaId: string,
    rating: number,
    comment?: string,
  ): Promise<void> {
    return request.post(`/personas/${personaId}/rating`, {
      rating,
      comment,
    });
  },

  /**
   * 获取人格评价
   */
  getPersonaRatings(
    personaId: string,
    page = 0,
    size = 20,
  ): Promise<
    PageResponse<{
      id: string;
      userId: string;
      username: string;
      rating: number;
      comment?: string;
      createdAt: string;
    }>
  > {
    return request.get(`/personas/${personaId}/ratings`, { page, size });
  },

  /**
   * 获取人格统计信息
   */
  getPersonaStats(personaId: string): Promise<{
    totalSessions: number;
    totalMessages: number;
    averageRating: number;
    totalRatings: number;
    favoriteCount: number;
    usageGrowth: number;
    popularityRank: number;
    lastUsed: string;
  }> {
    return request.get(`/personas/${personaId}/stats`);
  },

  /**
   * 测试人格
   */
  testPersona(
    personaId: string,
    testMessage: string,
  ): Promise<{
    response: string;
    responseTime: number;
    tokensUsed: number;
  }> {
    return request.post(
      `/personas/${personaId}/test`,
      {
        message: testMessage,
      },
      {
        showLoading: true,
        loadingText: "测试中...",
      },
    );
  },

  /**
   * 导出人格配置
   */
  exportPersona(personaId: string): Promise<void> {
    return request.download(
      `/personas/${personaId}/export`,
      {},
      `persona_${personaId}.json`,
    );
  },

  /**
   * 导入人格配置
   */
  importPersona(file: File): Promise<Persona> {
    const formData = new FormData();
    formData.append("file", file);

    return request.upload("/personas/import", formData, {
      showLoading: true,
      loadingText: "导入中...",
    });
  },

  /**
   * 分享人格
   */
  sharePersona(
    personaId: string,
    options: {
      isPublic: boolean;
      allowClone: boolean;
      description?: string;
    },
  ): Promise<{
    shareId: string;
    shareUrl: string;
  }> {
    return request.post(`/personas/${personaId}/share`, options);
  },

  /**
   * 获取分享的人格
   */
  getSharedPersona(shareId: string): Promise<Persona> {
    return request.get(`/personas/shared/${shareId}`);
  },

  /**
   * 从分享链接添加人格
   */
  addSharedPersona(shareId: string, customName?: string): Promise<Persona> {
    return request.post(
      "/personas/add-shared",
      {
        shareId,
        customName,
      },
      {
        showLoading: true,
        loadingText: "添加中...",
      },
    );
  },

  /**
   * 获取人格模板
   */
  getPersonaTemplates(): Promise<
    Array<{
      id: string;
      name: string;
      description: string;
      category: string;
      systemPrompt: string;
      config: Record<string, any>;
      tags: string[];
      difficulty: "beginner" | "intermediate" | "advanced";
    }>
  > {
    return request.get("/personas/templates");
  },

  /**
   * 从模板创建人格
   */
  createFromTemplate(
    templateId: string,
    customizations: {
      name: string;
      description?: string;
      systemPrompt?: string;
      config?: Record<string, any>;
    },
  ): Promise<Persona> {
    return request.post(
      "/personas/from-template",
      {
        templateId,
        ...customizations,
      },
      {
        showLoading: true,
        loadingText: "创建中...",
      },
    );
  },

  /**
   * 获取人格使用历史
   */
  getUsageHistory(
    personaId: string,
    period: "day" | "week" | "month" = "week",
  ): Promise<
    Array<{
      date: string;
      sessions: number;
      messages: number;
      averageRating: number;
    }>
  > {
    return request.get(`/personas/${personaId}/usage-history`, { period });
  },

  /**
   * 获取我创建的人格
   */
  getMyPersonas(page = 0, size = 20): Promise<PageResponse<Persona>> {
    return request.get("/personas/my", { page, size });
  },

  /**
   * 批量操作人格
   */
  batchOperation(
    operation: "activate" | "deactivate" | "delete",
    personaIds: string[],
  ): Promise<void> {
    return request.post(
      "/personas/batch",
      {
        operation,
        personaIds,
      },
      {
        showLoading: true,
        loadingText: "处理中...",
      },
    );
  },
};
